package com.yijumao.shop.service.impl;

import com.yijumao.shop.domain.ItemCat;
import com.yijumao.shop.mapper.ItemCatMapper;
import com.yijumao.shop.service.ItemCatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class ItemCatServiceImpl implements ItemCatService {

    @Autowired
    private ItemCatMapper itemCatMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public int deleteByPrimaryKey(Integer cid) {
        return 0;
    }

    @Override
    public int insert(ItemCat record) {
        return 0;
    }

    @Override
    public ItemCat selectByPrimaryKey(Integer cid) {
        return itemCatMapper.selectByPrimaryKey(cid);
    }

    @Override
    public List<ItemCat> selectAll() {
        return null;
    }

    @Override
    public int updateByPrimaryKey(ItemCat record) {
        return 0;
    }

    @Override
    public List<ItemCat> selectAllByStatus(int status) {
        List<ItemCat> itemCats = null;
        try {
            //从redis中获取存放分类信息的缓存 要用index方法！！！！
            itemCats = (List<ItemCat>) redisTemplate.opsForList().index("itemCats",-1);
            //没有缓存，从数据库中获取并存入缓存
            if(itemCats==null || itemCats.isEmpty()){
                itemCats = itemCatMapper.selectAllByStatus(status);
                redisTemplate.opsForList().leftPush("itemCats",itemCats);
            }
        } catch (Exception e) {
            //连接服务器有异常
            itemCats = itemCatMapper.selectAllByStatus(status);
            e.printStackTrace();
        } finally {
            return itemCats;
        }
    }
}
